import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * DRG/DIP日志类型定义
 */
export interface LogDrgDip {
  id: number
  caseId: string
  patientId: number
  patientName: string
  admissionId: number
  drgCode?: string
  dipCode?: string
  diseaseCodes: string[]
  operationCodes: string[]
  cost: number
  status: 'PENDING' | 'PROCESSED' | 'REJECTED'
  createTime: string
  processTime?: string
}

/**
 * DRG/DIP日志查询参数
 */
export interface LogDrgDipSearchParams extends PageParams {
  caseId?: string
  patientName?: string
  status?: 'PENDING' | 'PROCESSED' | 'REJECTED'
  startDate?: string
  endDate?: string
}

/**
 * 获取DRG/DIP日志列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchLogDrgDips = async (params: LogDrgDipSearchParams): Promise<PageResult<LogDrgDip>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<LogDrgDip>>>('/api/log-drg-dips', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取DRG/DIP日志失败')
    throw error
  }
}

/**
 * 获取DRG/DIP日志详情
 * @param id 日志ID
 * @returns 日志详情
 */
export const getLogDrgDip = async (id: number): Promise<LogDrgDip> => {
  try {
    const { data } = await request.get<BaseResponse<LogDrgDip>>(`/api/log-drg-dips/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取DRG/DIP日志详情失败')
    throw error
  }
}

/**
 * 处理DRG/DIP日志
 * @param id 日志ID
 * @param action 处理动作
 */
export const processLogDrgDip = async (id: number, action: 'APPROVE' | 'REJECT'): Promise<void> => {
  try {
    await request.patch(`/api/log-drg-dips/${id}/process`, { action })
    ElMessage.success(action === 'APPROVE' ? 'DRG/DIP日志审核通过' : 'DRG/DIP日志已拒绝')
  } catch (error) {
    ElMessage.error('处理DRG/DIP日志失败')
    throw error
  }
}

/**
 * 批量处理DRG/DIP日志
 * @param ids 日志ID数组
 * @param action 处理动作
 */
export const batchProcessLogDrgDips = async (ids: number[], action: 'APPROVE' | 'REJECT'): Promise<void> => {
  try {
    await request.patch('/api/log-drg-dips/batch-process', { ids, action })
    ElMessage.success(`成功处理${ids.length}条DRG/DIP日志')
  } catch (error) {
    ElMessage.error('批量处理DRG/DIP日志失败')
    throw error
  }
}

// 缓存最近请求的日志数据
const logDrgDipCache = new Map<number, LogDrgDip>()

/**
 * 获取DRG/DIP日志详情（带缓存）
 * @param id 日志ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 日志详情
 */
export const getLogDrgDipWithCache = async (id: number, forceRefresh = false): Promise<LogDrgDip> => {
  if (!forceRefresh && logDrgDipCache.has(id)) {
    return logDrgDipCache.get(id)!
  }

  const logDrgDip = await getLogDrgDip(id)
  logDrgDipCache.set(id, logDrgDip)
  return logDrgDip
}
